package com.example.h1nson.realphotography.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.example.h1nson.realphotography.R;
import com.example.h1nson.realphotography.adapter.CommentsAdapter;
import com.example.h1nson.realphotography.asyncTask.CommentAsyTask;
import com.example.h1nson.realphotography.asyncTask.PhotoDetailAsynTask;
import com.example.h1nson.realphotography.config.ConfigURL;
import com.example.h1nson.realphotography.config.GetCurrentUser;
import com.example.h1nson.realphotography.interface_photo.OnDataFinishedListener;
import com.example.h1nson.realphotography.util.AsyncImageLoader;

import org.json.JSONException;
import org.json.JSONObject;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by H1nson on 2016/5/16.
 */
public class PhotoDetailActivity extends AppCompatActivity {
    private TextView textViewOwnerName;
    private ImageView imageView,iamgeView_owner;
    private TextView active;
    private TextView passive;
    private TextView textAddress;
    private TextView textDate;
    private EditText edt_word;
    private Button btn_submit;
    private ListView mCommentListView;
    private int photoId;
    private String photoURL;
    private String ownerURL;
    private String ownerName;
    private String address;
    private String date;
    private int activeNum;
    private int passiveNum;
    private CommentsAdapter commentsAdapter;
    private List<Map> listComment =new ArrayList<Map>();
    private Map map;
    private boolean mActive,mPassive,mCollect;
    private ImageButton btn_mActive,btn_mPassive,btn_mCollect;
    private ScrollView scrollview;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.photo_item);
        btn_submit = (Button)findViewById(R.id.btn_photo_item);
        btn_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btn_submit.setEnabled(false);
                String commentStr = edt_word.getText().toString();
                if(commentStr.toString().equals("")){
                    //do nothing
                    btn_submit.setEnabled(true);
                }else {
                    map = new HashMap();
                    map.put("name", GetCurrentUser.currentUser.getUserName());
                    map.put("headURL", GetCurrentUser.currentUser.getUserHead());
                    map.put("comment", commentStr.toString());
                    Timestamp time = new Timestamp(System.currentTimeMillis());
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    map.put("time", sdf.format(time));
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put("function",0);
                        jsonObject.put("curUserId", GetCurrentUser.currentUser.getUserId());
                        jsonObject.put("photoId", photoId);
                        jsonObject.put("photoTime", System.currentTimeMillis());
                        jsonObject.put("comment", commentStr.toString());
                    }catch (JSONException e){
                        e.printStackTrace();
                        btn_submit.setEnabled(true);
                    }
                    CommentAsyTask commentAsyTask = new CommentAsyTask(jsonObject);
                    commentAsyTask.setOnDataFinishedListener(new OnDataFinishedListener() {
                        @Override
                        public void onDataSuccessfully(Object data) {
                            if(data.toString().equals("success")){
                                listComment.add(map);
                                commentsAdapter.notifyDataSetChanged();
                                setListViewHeightBasedOnChildren(mCommentListView);
                                Handler handler = new Handler();
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        InputMethodManager m=(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                                        m.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                                        edt_word.setText("");
                                        scrollview.setFocusable(true);
                                        scrollview.setFocusableInTouchMode(true);
                                        scrollview.requestFocus();
                                        scrollview.requestFocusFromTouch();
                                        scrollview.fullScroll(ScrollView.FOCUS_DOWN);

                                    }
                                });
                            }
                            btn_submit.setEnabled(true);
                        }

                        @Override
                        public void onDataFailed() {
                            btn_submit.setEnabled(true);
                        }
                    });
                    commentAsyTask.execute();
                }
            }
        });
        initUI();
        setActiveAndPassiveAndCollect();
    }
    private void initUI(){
        scrollview = (ScrollView)findViewById(R.id.photo_item_scrollview) ;
        textViewOwnerName = (TextView)findViewById(R.id.TextviewOwnerName);
        imageView = (ImageView)findViewById(R.id.imageview_photo_ltem);
        iamgeView_owner = (ImageView)findViewById(R.id.owner_image);
        active = (TextView)findViewById(R.id.active_com_num);
        passive = (TextView)findViewById(R.id.passtive_com_num);
        textAddress = (TextView)findViewById(R.id.textview_address);
        textDate = (TextView)findViewById(R.id.textview_date);
        edt_word = (EditText)findViewById(R.id.edt_submit);
        btn_mActive = (ImageButton)findViewById(R.id.btn_active) ;
        btn_mPassive = (ImageButton)findViewById(R.id.btn_passtive);
        btn_mCollect = (ImageButton)findViewById(R.id.btn_collect);
        WindowManager wm = this.getWindowManager();
        int width = wm.getDefaultDisplay().getWidth();
        ViewGroup.LayoutParams ps = imageView.getLayoutParams();
        ps.height = (int)width*9/10;
        ps.width = (int)width*9/10;
        imageView.setLayoutParams(ps);
        imageView.setImageResource(R.drawable.camera);
        iamgeView_owner.setImageResource(R.drawable.user_image);
        getPhotoMessage();

    }
    private void getPhotoMessage(){
        Intent intent =getIntent();
        photoId =intent.getIntExtra("photoId",0);
        PhotoDetailAsynTask photoDetailAsynTask = new PhotoDetailAsynTask(photoId);
        photoDetailAsynTask.setOnDataFinishedListener(new OnDataFinishedListener() {
            @Override
            public void onDataSuccessfully(Object data) {
                JSONObject jsonObject;
                try {
                    jsonObject = new JSONObject(data.toString());
                    photoURL = jsonObject.getString("photoURL");
                    ownerName = jsonObject.getString("ownerName");
                    ownerURL = jsonObject.getString("ownerURL");
                    address = jsonObject.getString("address");
                    date = jsonObject.getString("date");
                    activeNum = jsonObject.getInt("activeNum");
                    passiveNum= jsonObject.getInt("passiveNum");
                    mActive = jsonObject.getBoolean("active");
                    mPassive = jsonObject.getBoolean("passive");
                    mCollect = jsonObject.getBoolean("collect");
                    if(mActive){
                        btn_mActive.setImageResource(R.drawable.ic_active_clicked);
                    }
                    if(mPassive){
                        btn_mPassive.setImageResource(R.drawable.ic_passive_clicked);
                    }
                    if(mCollect){
                        btn_mCollect.setImageResource(R.drawable.ic_collect_clicked);
                    }
                    int size = jsonObject.getInt("messageSize");
                    for(int i= 0;i<size;i++){
                        Map map = new HashMap();
                        map.put("name",jsonObject.getString("name"+i));
                        map.put("headURL",jsonObject.getString("headURL"+i));
                        map.put("comment",jsonObject.getString("comment"+i));
                        map.put("time",jsonObject.getString("time"+i));
                        listComment.add(map);
                    }
                    System.out.println("成功");
                    datafinished();
                    comment();
                }catch (JSONException e){
                    e.printStackTrace();
                }
            }
            @Override
            public void onDataFailed() {
                System.out.println("失败");
            }
        });
        photoDetailAsynTask.execute();

    }
    public void comment(){
        mCommentListView = (ListView)findViewById(R.id.comment_listview);
        commentsAdapter = new CommentsAdapter(this,listComment);
        System.out.println(listComment.toString());
        mCommentListView.setAdapter(commentsAdapter);
        setListViewHeightBasedOnChildren(mCommentListView);
    }
    public void datafinished(){

        AsyncImageLoader asyncImageLoader0 = new AsyncImageLoader();
        String headUrl = ConfigURL.headURL+ownerURL;

        Drawable cachedImage0 = asyncImageLoader0.loadDrawable(headUrl, new AsyncImageLoader.ImageCallback() {
            public void imageLoaded(Drawable imageDrawable, String imageUrl) {
                if (imageDrawable == null) {
                    //imageView.setImageResource(R.drawable.icon);
                    //imageDrawable = getResources().getDrawable(R.drawable.user_image);
                }else
                    iamgeView_owner.setImageDrawable(imageDrawable);
            }
        });

        AsyncImageLoader asyncImageLoader = new AsyncImageLoader();
        String imageUrl = ConfigURL.photoURL+photoURL;

        Drawable cachedImage = asyncImageLoader.loadDrawable(imageUrl, new AsyncImageLoader.ImageCallback() {
            public void imageLoaded(Drawable imageDrawable, String imageUrl) {
                if (imageDrawable == null) {
                    //imageView.setImageResource(R.drawable.icon);
                    //imageDrawable = getResources().getDrawable(R.drawable.user_image);
                }else
                    imageView.setImageDrawable(imageDrawable);
            }
        });

        textViewOwnerName.setText(ownerName);
        textAddress.setText(address);
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date photoDate  = sdf.parse(date);
//            SimpleDateFormat myFmt=new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒 E ");
            SimpleDateFormat myFmt=new SimpleDateFormat("yyyy年MM月dd日");
            textDate.setText(myFmt.format(photoDate));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        active.setText(String.valueOf(activeNum));
        passive.setText(String.valueOf(passiveNum));
    }
    public void setActiveAndPassiveAndCollect(){
        btn_mActive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mActive = !mActive;
                btn_mActive.setEnabled(false);
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("function", 1);
                    jsonObject.put("curUserId",GetCurrentUser.currentUser.getUserId());
                    jsonObject.put("photoId",photoId);
                    jsonObject.put("active",mActive);
                    CommentAsyTask commentAsyTask = new CommentAsyTask(jsonObject);
                    commentAsyTask.setOnDataFinishedListener(new OnDataFinishedListener() {
                        @Override
                        public void onDataSuccessfully(Object data) {
                                String result = data.toString();
                                if(result.equals("success")){
                                    if(mActive) {
                                        activeNum++;
                                        btn_mActive.setImageResource(R.drawable.ic_active_clicked);
                                    }else {
                                        activeNum--;
                                        btn_mActive.setImageResource(R.drawable.ic_active);
                                    }
                                    active.setText(String.valueOf(activeNum));
                                }
                            btn_mActive.setEnabled(true);
                        }

                        @Override
                        public void onDataFailed() {
                            btn_mActive.setEnabled(true);
                        }
                    });
                    commentAsyTask.execute();
                }catch (JSONException e){
                    e.printStackTrace();
                    btn_mActive.setEnabled(true);
                }
            }
        });

        btn_mPassive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPassive = !mPassive;
                btn_mPassive.setEnabled(false);
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("function", 2);
                    jsonObject.put("curUserId",GetCurrentUser.currentUser.getUserId());
                    jsonObject.put("photoId",photoId);
                    jsonObject.put("passive",mPassive);
                    CommentAsyTask commentAsyTask = new CommentAsyTask(jsonObject);
                    commentAsyTask.setOnDataFinishedListener(new OnDataFinishedListener() {
                        @Override
                        public void onDataSuccessfully(Object data) {
                            String result = data.toString();
                            if(result.equals("success")){
                                if(mPassive) {
                                    passiveNum++;
                                    btn_mPassive.setImageResource(R.drawable.ic_passive_clicked);
                                }else {
                                    passiveNum--;
                                    btn_mPassive.setImageResource(R.drawable.ic_passive);
                                }
                                passive.setText(String.valueOf(passiveNum));
                            }
                            btn_mPassive.setEnabled(true);
                        }
                        @Override
                        public void onDataFailed() {
                            btn_mPassive.setEnabled(true);
                        }
                    });
                    commentAsyTask.execute();
                }catch (JSONException e){
                    e.printStackTrace();
                    btn_mPassive.setEnabled(true);
                }
            }
        });

        btn_mCollect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCollect = !mCollect;
                btn_mCollect.setEnabled(false);
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("function", 3);
                    jsonObject.put("curUserId",GetCurrentUser.currentUser.getUserId());
                    jsonObject.put("photoId",photoId);
                    jsonObject.put("collect",mCollect);
                    CommentAsyTask commentAsyTask = new CommentAsyTask(jsonObject);
                    commentAsyTask.setOnDataFinishedListener(new OnDataFinishedListener() {
                        @Override
                        public void onDataSuccessfully(Object data) {
                                String result = data.toString();
                                if(result.equals("success")){
                                    if(mCollect) {

                                        btn_mCollect.setImageResource(R.drawable.ic_collect_clicked);
                                    }else
                                        btn_mCollect.setImageResource(R.drawable.ic_collect);
                                }
                            btn_mCollect.setEnabled(true);
                        }

                        @Override
                        public void onDataFailed() {
                            btn_mCollect.setEnabled(true);
                        }
                    });
                    commentAsyTask.execute();
                }catch (JSONException e){
                    e.printStackTrace();
                    btn_mCollect.setEnabled(true);
                }
            }
        });
    }
    public static void setListViewHeightBasedOnChildren(ListView listView) {
        if(listView == null) return;

        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }
        if (listAdapter.getCount() == 0) {
            // pre-condition
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }
}

